package main

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"net/http"
	"strconv"
	"time"
)

type (
	UserFeedback struct {
		Address    string `json:"address"`
		Username   string `json:"username"`
		Mobile     string `json:"mobile"`
		Pic        string `json:"pic"`
		Video      string `json:"video"`
		Id         int    `json:"id"`
		CreateTime int    `json:"createTime"`
	}

	Resp struct {
		Code int    `json:"code"`
		Msg  string `json:"msg"`
	}

	PageResp struct {
		Count int            `json:"count"`
		List  []UserFeedback `json:"list"`
	}
)

var (
	dbIns *gorm.DB
)

func init() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "mysql:5da98a424f95b710@tcp(106.52.180.164:13155)/user-feedback?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	dbIns = db
}

func setupRouter() *gin.Engine {
	// Disable Console Color
	// gin.DisableConsoleColor()
	r := gin.Default()

	// Ping test
	r.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "pong")
	})

	// 上传
	r.POST("/feedback/upload-user", func(c *gin.Context) {
		picFile, err := c.FormFile("pic")
		if err != nil {
			log.Println(err)
		}
		mobile := c.PostForm("mobile")
		var exist int64
		dbIns.Table("user-feedback").Where("mobile=?", mobile).Where("create_time>?", int(time.Now().Unix())-1800).Count(&exist)
		if exist > 0 {
			c.JSON(http.StatusOK, &Resp{
				Code: 1,
				Msg:  "以重复提交",
			})
			return
		}
		picDst := "./pic/" + picFile.Filename
		// 上传文件至指定的完整文件路径
		c.SaveUploadedFile(picFile, picDst)
		videoFile, _ := c.FormFile("video")
		videoDst := "./video/" + videoFile.Filename
		// 上传文件至指定的完整文件路径
		c.SaveUploadedFile(videoFile, videoDst)
		address := c.PostForm("address")
		username := c.PostForm("username")

		d := &UserFeedback{
			Address:    address,
			Username:   username,
			Mobile:     mobile,
			Pic:        "/pic/" + picFile.Filename,
			Video:      "/video/" + videoFile.Filename,
			CreateTime: int(time.Now().Unix()),
		}
		err = dbIns.Table("user-feedback").Create(d).Error
		if err != nil {
			log.Println(err)
		}

		c.JSON(http.StatusOK, &Resp{})
	})

	// 后台获取列表
	r.GET("/feedback/list", func(c *gin.Context) {
		pageStr := c.DefaultQuery("page", "1")
		sizeStr := c.DefaultQuery("size", "10")
		page, _ := strconv.Atoi(pageStr)
		size, _ := strconv.Atoi(sizeStr)
		var count int64 // 统计总的记录数
		dbIns.Table("user-feedback").Count(&count)
		results := []UserFeedback{}
		dbIns.Table("user-feedback").Order("id desc").Offset((page - 1) * size).Limit(size).Find(&results)
		pageResp := &PageResp{
			Count: int(count),
			List:  results,
		}
		c.JSON(http.StatusOK, pageResp)
	})

	return r
}

func main() {
	r := setupRouter()
	r.Run(":1081")
}
